package com.ruoyi.websocket.service;

import com.ruoyi.websocket.domain.ReceiveMessage;
import com.ruoyi.websocket.domain.WebSocketMessage;
import com.ruoyi.websocket.handler.MessageWebSocketHandler;
import com.ruoyi.system.service.ISpffVideosService;
import com.ruoyi.system.domain.SpffVideos;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * WebSocket消息处理服务
 * 
 * @author ruoyi
 */
@Service
public class WebSocketMessageService {

    @Autowired
    private ISpffVideosService spffVideosService;

    /**
     * 处理点赞消息
     */
    public void handleLikeMessage(ReceiveMessage receiveMessage, Long currentUserId) {
        try {
            // 获取视频信息
            SpffVideos video = spffVideosService.selectSpffVideosById(receiveMessage.getVideoId());
            if (video == null) {
                return;
            }

            // 构建通知消息
            String content = receiveMessage.getUserName() + " 点赞了你的视频《" + video.getTitle() + "》";
            WebSocketMessage notification = new WebSocketMessage("notification", content);

            // 发送给视频作者（如果不是自己点赞自己的视频）
            if (!currentUserId.equals(video.getUserId())) {
                MessageWebSocketHandler.sendMessageToUser(video.getUserId(), notification);
                System.out.println("发送点赞通知：" + content);
            }

        } catch (Exception e) {
            System.err.println("处理点赞消息失败：" + e.getMessage());
        }
    }

    /**
     * 处理评论消息
     */
    public void handleCommentMessage(ReceiveMessage receiveMessage, Long currentUserId) {
        try {
            // 获取视频信息
            SpffVideos video = spffVideosService.selectSpffVideosById(receiveMessage.getVideoId());
            if (video == null) {
                return;
            }

            // 构建通知消息
            String content = receiveMessage.getUserName() + " 评论了你的视频《" + video.getTitle() + "》：" + receiveMessage.getContent();
            WebSocketMessage notification = new WebSocketMessage("notification", content);

            // 发送给视频作者（如果不是自己评论自己的视频）
            if (!currentUserId.equals(video.getUserId())) {
                MessageWebSocketHandler.sendMessageToUser(video.getUserId(), notification);
                System.out.println("发送评论通知：" + content);
            }

        } catch (Exception e) {
            System.err.println("处理评论消息失败：" + e.getMessage());
        }
    }

    /**
     * 处理关注消息
     */
    public void handleFollowMessage(ReceiveMessage receiveMessage, Long currentUserId) {
        try {
            // 构建通知消息
            String content = receiveMessage.getUserName() + " 关注了你";
            WebSocketMessage notification = new WebSocketMessage("notification", content);

            // 发送给被关注的用户
            if (receiveMessage.getUserId() != null && !currentUserId.equals(receiveMessage.getUserId())) {
                MessageWebSocketHandler.sendMessageToUser(receiveMessage.getUserId(), notification);
                System.out.println("发送关注通知：" + content);
            }

        } catch (Exception e) {
            System.err.println("处理关注消息失败：" + e.getMessage());
        }
    }

    /**
     * 处理一般消息
     */
    public void handleGeneralMessage(ReceiveMessage receiveMessage, Long currentUserId) {
        try {
            // 构建消息
            WebSocketMessage message = new WebSocketMessage("message", receiveMessage.getContent());

            // 如果指定了接收用户ID，发送给指定用户，否则广播
            if (receiveMessage.getUserId() != null) {
                MessageWebSocketHandler.sendMessageToUser(receiveMessage.getUserId(), message);
                System.out.println("发送私信：" + receiveMessage.getContent());
            } else {
                MessageWebSocketHandler.broadcastMessage(message);
                System.out.println("广播消息：" + receiveMessage.getContent());
            }

        } catch (Exception e) {
            System.err.println("处理一般消息失败：" + e.getMessage());
        }
    }

    /**
     * 发送点赞通知（外部调用）
     */
    public void sendLikeNotification(Long videoId, Long likeUserId, String likeUserName) {
        try {
            SpffVideos video = spffVideosService.selectSpffVideosById(videoId);
            if (video != null && !likeUserId.equals(video.getUserId())) {
                String content = likeUserName + " 点赞了你的视频《" + video.getTitle() + "》";
                
                // 创建包含发送者和接收者信息的通知
                WebSocketMessage notification = new WebSocketMessage(
                    "notification", 
                    content,
                    likeUserId,           // 发送者ID
                    likeUserName,         // 发送者名称
                    video.getUserId(),    // 接收者ID
                    getUserNameById(video.getUserId()) // 接收者名称
                );
                
                MessageWebSocketHandler.sendMessageToUser(video.getUserId(), notification);
                System.out.println("发送点赞通知：" + likeUserName + " → " + getUserNameById(video.getUserId()));
            }
        } catch (Exception e) {
            System.err.println("发送点赞通知失败：" + e.getMessage());
        }
    }

    /**
     * 发送收藏通知（外部调用）
     */
    public void sendCollectNotification(Long videoId, Long collectUserId, String collectUserName) {
        try {
            SpffVideos video = spffVideosService.selectSpffVideosById(videoId);
            if (video != null && !collectUserId.equals(video.getUserId())) {
                String content = collectUserName + " 收藏了你的视频《" + video.getTitle() + "》";
                
                // 创建包含发送者和接收者信息的通知
                WebSocketMessage notification = new WebSocketMessage(
                    "notification", 
                    content,
                    collectUserId,        // 发送者ID
                    collectUserName,      // 发送者名称
                    video.getUserId(),    // 接收者ID
                    getUserNameById(video.getUserId()) // 接收者名称
                );
                
                MessageWebSocketHandler.sendMessageToUser(video.getUserId(), notification);
                System.out.println("发送收藏通知：" + collectUserName + " → " + getUserNameById(video.getUserId()));
            }
        } catch (Exception e) {
            System.err.println("发送收藏通知失败：" + e.getMessage());
        }
    }

    /**
     * 根据用户ID获取用户名
     */
    private String getUserNameById(Long userId) {
        try {
            // 这里可以调用用户服务获取用户名，暂时返回用户ID字符串
            return "用户" + userId;
        } catch (Exception e) {
            return "未知用户";
        }
    }
}
